'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Loader2 } from 'lucide-react'
import ReactECharts from 'echarts-for-react'

interface TemperatureData {
  timestamp: number
  temperature: number
  calibratedTemperature?: number // 校准后的温度
}

interface TemperatureChartProps {
  userId: string
  selectedDate: string
}

export function TemperatureChart({ userId, selectedDate }: TemperatureChartProps) {
  const [temperatureData, setTemperatureData] = useState<TemperatureData[]>([])
  const [loading, setLoading] = useState(false)
  const [calibrationData, setCalibratedData] = useState<{
    baseline_temp: number
    anchor_offset: number
  } | null>(null)

  // 获取温度校准数据
  const fetchCalibrationData = async () => {
    try {
      const response = await fetch(`/api/health/temperature-calibration?userId=${userId}`)
      
      if (!response.ok) {
        console.warn('获取温度校准数据失败')
        return
      }

      const result = await response.json()
      console.log('温度校准数据:', result)

      if (result.success && result.data) {
        setCalibratedData({
          baseline_temp: result.data.baseline_temp,
          anchor_offset: result.data.anchor_offset
        })
      }
    } catch (error) {
      console.error('获取温度校准数据失败:', error)
    }
  }

  // 获取温度数据
  const fetchTemperatureData = async () => {
    try {
      // 数据库中的时间戳是本地时间戳，直接构造本地时间范围
      const selectedDateObj = new Date(selectedDate)
      
      // 构造本地时间的开始和结束时间戳
      const startDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0)
      const endDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0)
      
      console.log('温度查询时间范围:', {
        selectedDate,
        startDate: startDate.toLocaleString('zh-CN'),
        endDate: endDate.toLocaleString('zh-CN'),
        startDateISO: startDate.toISOString(),
        endDateISO: endDate.toISOString(),
        startTimestamp: startDate.getTime(),
        endTimestamp: endDate.getTime()
      })

      const response = await fetch(`/api/health?userId=${userId}&dataType=temperature&startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`)
      
      if (!response.ok) {
        throw new Error('Failed to fetch temperature data')
      }

      const data = await response.json()
      console.log('温度 API响应:', data)

      // 提取温度数据
      const logs = data.data?.logs || data.logs || []
      console.log('温度 提取的logs:', {
        logsLength: logs.length,
        firstLog: logs[0] || null,
        lastLog: logs[logs.length - 1] || null
      })

      const processedData = processTemperatureData(logs)
      console.log('处理后的温度数据:', {
        originalLogsCount: logs.length,
        processedDataCount: processedData.length,
        firstProcessedData: processedData[0] || null,
        lastProcessedData: processedData[processedData.length - 1] || null
      })
      
      // 如果有校准数据，计算校准后的温度
      const dataWithCalibration = addCalibratedTemperature(processedData)
      setTemperatureData(dataWithCalibration)
    } catch (error) {
      console.error('获取温度数据失败:', error)
      setTemperatureData([])
    }
  }

  // 滑动窗口离群值检测算法
  const cleanRawData = (rawPoints: {timestamp: number, raw_temp: number}[]): {timestamp: number, raw_temp: number}[] => {
    if (rawPoints.length === 0) return []
    
    // 第一步：基本范围过滤
    const basicFiltered = rawPoints.filter(p => p.raw_temp > 32 && p.raw_temp < 45)
    
    if (basicFiltered.length < 3) return basicFiltered
    
    // 第二步：滑动窗口离群值检测
    const windowSize = Math.min(7, Math.floor(basicFiltered.length / 3)) // 动态窗口大小
    const cleanedPoints: {timestamp: number, raw_temp: number}[] = []
    
    for (let i = 0; i < basicFiltered.length; i++) {
      const currentPoint = basicFiltered[i]
      
      // 确定窗口范围
      const windowStart = Math.max(0, i - Math.floor(windowSize / 2))
      const windowEnd = Math.min(basicFiltered.length - 1, i + Math.floor(windowSize / 2))
      
      // 获取窗口内的数据点
      const windowPoints = basicFiltered.slice(windowStart, windowEnd + 1)
      const windowTemps = windowPoints.map(p => p.raw_temp)
      
      // 计算窗口内的统计信息
      const mean = windowTemps.reduce((sum, temp) => sum + temp, 0) / windowTemps.length
      const variance = windowTemps.reduce((sum, temp) => sum + Math.pow(temp - mean, 2), 0) / windowTemps.length
      const stdDev = Math.sqrt(variance)
      
      // 离群值检测：使用2.5个标准差作为阈值
      const threshold = 2.5
      const lowerBound = mean - threshold * stdDev
      const upperBound = mean + threshold * stdDev
      
      // 如果当前点在合理范围内，保留它
      if (currentPoint.raw_temp >= lowerBound && currentPoint.raw_temp <= upperBound) {
        cleanedPoints.push(currentPoint)
      } else {
        console.log(`过滤离群值: ${currentPoint.raw_temp}℃ (范围: ${lowerBound.toFixed(1)}℃ - ${upperBound.toFixed(1)}℃)`)
      }
    }
    
    console.log(`数据清洗: ${rawPoints.length} → ${basicFiltered.length} → ${cleanedPoints.length}`)
    return cleanedPoints
  }

  // 添加校准后的温度（带数据清洗）
  const addCalibratedTemperature = (data: TemperatureData[]): TemperatureData[] => {
    if (!calibrationData) {
      return data
    }

    // 先计算所有校准后的温度
    const dataWithCalibration = data.map(item => ({
      ...item,
      calibratedTemperature: item.temperature + calibrationData.anchor_offset
    }))

    // 准备校准后温度数据进行清洗
    const calibratedRawPoints = dataWithCalibration
      .filter(item => item.calibratedTemperature !== undefined)
      .map(item => ({
        timestamp: item.timestamp,
        raw_temp: item.calibratedTemperature!
      }))

    // 清洗校准后的温度数据
    const cleanedCalibratedPoints = cleanRawData(calibratedRawPoints)
    const cleanedTimestamps = new Set(cleanedCalibratedPoints.map(p => p.timestamp))

    // 返回清洗后的数据：保留所有原始温度，但只保留清洗后的校准温度
    return dataWithCalibration.map(item => ({
      ...item,
      calibratedTemperature: cleanedTimestamps.has(item.timestamp) ? item.calibratedTemperature : undefined
    }))
  }

  // 处理温度数据
  const processTemperatureData = (logs: any[]): TemperatureData[] => {
    const temperaturePoints: TemperatureData[] = []
    
    logs.forEach((log) => {
      const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data

      // 处理时间戳：优先使用logData中的ts，如果没有则使用log的timestamp
      let timestamp = parseInt(logData.ts) || parseInt(log.timestamp)
      
      // 如果时间戳是10位（秒级），转换为13位（毫秒级）
      if (timestamp < 10000000000) {
        timestamp = timestamp * 1000
      }
      
      // 检查时间戳是否在合理范围内（2020-2070年之间）
      const minValidTimestamp = new Date('2020-01-01').getTime()
      const maxValidTimestamp = new Date('2070-12-31').getTime()
      
      if (timestamp < minValidTimestamp || timestamp > maxValidTimestamp) {
        console.warn('跳过无效时间戳:', {
          originalTimestamp: logData.ts || log.timestamp,
          convertedTimestamp: timestamp,
          timestampDate: new Date(timestamp).toISOString()
        })
        return
      }
      
      // 提取温度数据
      const temperatureValue = parseFloat(logData.temperature) || 0
      
      if (temperatureValue > 0) {
        temperaturePoints.push({
          timestamp,
          temperature: temperatureValue
        })
      }
    })

    return temperaturePoints.sort((a, b) => a.timestamp - b.timestamp)
  }

  // 生成温度图表配置
  const generateTemperatureChart = () => {
    if (temperatureData.length === 0) return null

    // 准备图表数据 - 不聚合，每个数据点单独显示
    const deviceTempData: [number, number][] = temperatureData.map(data => [data.timestamp, data.temperature])
    const calibratedTempData: [number, number][] = temperatureData
      .filter(data => data.calibratedTemperature !== undefined)
      .map(data => [data.timestamp, data.calibratedTemperature!])

    // 计算Y轴范围 - 包含原始温度和校准后温度
    const allTemperatures = [
      ...temperatureData.map(d => d.temperature),
      ...temperatureData.filter(d => d.calibratedTemperature !== undefined).map(d => d.calibratedTemperature!)
    ]
    const minTemp = allTemperatures.length > 0 ? Math.min(...allTemperatures) : 30
    const maxTemp = allTemperatures.length > 0 ? Math.max(...allTemperatures) : 40
    
    // 设置合理的温度范围，确保包含正常温度范围（36.1-37.2℃）
    const normalMinTemp = 36.1
    const normalMaxTemp = 37.2
    const yAxisMin = Math.max(30, Math.min(Math.floor(minTemp - 1), normalMinTemp - 0.5))
    const yAxisMax = Math.min(42, Math.max(Math.ceil(maxTemp + 1), normalMaxTemp + 0.5))

    return {
      title: {
        text: '温度分析',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          if (params && params.length > 0) {
            const time = new Date(params[0].value[0]).toLocaleString('zh-CN', {
              year: 'numeric',
              month: 'numeric',
              day: 'numeric',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false
            })
            
            let tooltipContent = `${time}<br/>`
            
            // 显示设备温度
            const deviceTempData = params.find((p: any) => p.seriesName === '设备温度')
            if (deviceTempData) {
              tooltipContent += `设备温度: ${deviceTempData.value[1].toFixed(1)}℃<br/>`
            }
            
            // 显示校准后温度
            const calibratedTempData = params.find((p: any) => p.seriesName === '校准后温度')
            if (calibratedTempData) {
              tooltipContent += `校准后温度: ${calibratedTempData.value[1].toFixed(1)}℃<br/>`
            }
            
            return tooltipContent
          }
          return ''
        }
      },
      legend: {
        data: calibratedTempData.length > 0 ? ['设备温度', '校准后温度', '正常范围'] : ['设备温度', '正常范围'],
        top: 30,
        formatter: (name: string) => {
          if (name === '正常最低温度' || name === '正常最高温度') {
            return '正常范围'
          }
          return name
        }
      },
      xAxis: {
        type: 'time',
        axisLabel: {
          formatter: (value: number) => {
            const date = new Date(value)
            return date.getHours().toString().padStart(2, '0') + ':00'
          }
        },
        min: () => {
          // 设置X轴范围为选择日期的00:00到24:00
          const selectedDateObj = new Date(selectedDate)
          return new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0).getTime()
        },
        max: () => {
          const selectedDateObj = new Date(selectedDate)
          return new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0).getTime()
        }
      },
      yAxis: {
        type: 'value',
        name: '温度 (℃)',
        min: yAxisMin,
        max: yAxisMax,
        axisLabel: {
          formatter: '{value}℃'
        }
      },
      series: [
        {
          name: '设备温度',
          type: 'line',
          data: deviceTempData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 4,
          lineStyle: {
            color: '#f59e0b', // 橙色，代表设备温度
            width: 2
          },
          itemStyle: {
            color: '#f59e0b'
          }
        },
        ...(calibratedTempData.length > 0 ? [{
          name: '校准后温度',
          type: 'line',
          data: calibratedTempData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color: '#ef4444', // 红色，代表校准后的核心体温
            width: 3
          },
          itemStyle: {
            color: '#ef4444'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(239, 68, 68, 0.3)' },
                { offset: 1, color: 'rgba(239, 68, 68, 0.1)' }
              ]
            }
          }
        }] : []),
        {
          name: '正常最低温度',
          type: 'line',
          data: [
            [new Date(selectedDate + 'T00:00:00').getTime(), 36.1],
            [new Date(selectedDate + 'T23:59:59').getTime(), 36.1]
          ],
          lineStyle: {
            color: '#22c55e', // 绿色，表示正常范围
            width: 2,
            type: 'dashed' // 虚线
          },
          symbol: 'none', // 不显示数据点
          silent: true // 不响应鼠标事件
        },
        {
          name: '正常最高温度',
          type: 'line',
          data: [
            [new Date(selectedDate + 'T00:00:00').getTime(), 37.2],
            [new Date(selectedDate + 'T23:59:59').getTime(), 37.2]
          ],
          lineStyle: {
            color: '#22c55e', // 绿色，表示正常范围
            width: 2,
            type: 'dashed' // 虚线
          },
          symbol: 'none', // 不显示数据点
          silent: true // 不响应鼠标事件
        }
      ]
    }
  }

  // 获取统计信息
  const getStatistics = () => {
    if (temperatureData.length === 0) {
      return {
        title: '温度统计',
        stats: [
          { label: '原始数据点', value: '0' },
          { label: '设备温度', value: '无数据' },
          { label: '校准后温度', value: '无数据' },
          { label: '温度状态', value: '无数据' }
        ]
      }
    }

    const deviceTemperatures = temperatureData.map(d => d.temperature)
    const avgDeviceTemp = deviceTemperatures.reduce((sum, t) => sum + t, 0) / deviceTemperatures.length
    
    // 校准后温度统计（清洗后的数据）
    const calibratedTemperatures = temperatureData
      .filter(d => d.calibratedTemperature !== undefined)
      .map(d => d.calibratedTemperature!)
    
    let calibratedStats = '无校准数据'
    let tempStatus = '未知'
    let dataQualityInfo = ''
    
    if (calibratedTemperatures.length > 0) {
      const avgCalibratedTemp = calibratedTemperatures.reduce((sum, t) => sum + t, 0) / calibratedTemperatures.length
      calibratedStats = `${avgCalibratedTemp.toFixed(1)}℃`
      
      // 数据质量信息
      const originalCount = temperatureData.length
      const cleanedCount = calibratedTemperatures.length
      const filterRate = ((originalCount - cleanedCount) / originalCount * 100).toFixed(1)
      dataQualityInfo = `${cleanedCount}/${originalCount} (过滤${filterRate}%)`
      
      // 评估校准后温度状态（基于正常体温范围36.1-37.2℃）
      const normalCount = calibratedTemperatures.filter(t => t >= 36.1 && t <= 37.2).length
      const lowCount = calibratedTemperatures.filter(t => t < 36.1).length
      const highCount = calibratedTemperatures.filter(t => t > 37.2).length
      
      if (lowCount > normalCount && lowCount > highCount) {
        tempStatus = '偏低'
      } else if (highCount > normalCount && highCount > lowCount) {
        tempStatus = '偏高'
      } else {
        tempStatus = '正常'
      }
    } else {
      dataQualityInfo = `0/${temperatureData.length} (无有效数据)`
    }

    return {
      title: '温度统计',
      stats: [
        { label: '有效数据点', value: dataQualityInfo },
        { label: '设备温度', value: `${avgDeviceTemp.toFixed(1)}℃` },
        { label: '校准后温度', value: calibratedStats },
        { label: '温度状态', value: tempStatus }
      ]
    }
  }

  // 数据获取
  useEffect(() => {
    if (!userId || !selectedDate) return

    setLoading(true)
    
    const fetchData = async () => {
      // 先获取校准数据，再获取温度数据
      await fetchCalibrationData()
      await fetchTemperatureData()
      setLoading(false)
    }

    fetchData()
  }, [userId, selectedDate])

  // 当校准数据变化时，重新计算校准后的温度
  useEffect(() => {
    if (temperatureData.length > 0) {
      const dataWithCalibration = addCalibratedTemperature(temperatureData)
      setTemperatureData(dataWithCalibration)
    }
  }, [calibrationData])

  const statistics = getStatistics()
  const chartConfig = generateTemperatureChart()

  return (
    <div className="space-y-4">
      {/* 图表区域 */}
      <Card>
        <CardHeader>
          <CardTitle>温度分析</CardTitle>
          <CardDescription>
            显示设备温度和校准后温度的变化趋势。橙色线为设备原始温度，红色线为校准后的核心体温（已过滤离群值），绿色虚线表示正常体温范围（36.1℃-37.2℃）
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">加载中...</span>
            </div>
          ) : chartConfig ? (
            <ReactECharts
              option={chartConfig}
              style={{ width: '100%', height: '400px' }}
              opts={{ renderer: 'canvas' }}
            />
          ) : (
            <div className="flex items-center justify-center h-64 text-gray-500">
              <div className="text-center">
                <p className="text-lg font-medium">暂无数据</p>
                <p className="text-sm">该日期没有皮肤温度数据</p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 统计信息 */}
      <Card>
        <CardHeader>
          <CardTitle>{statistics.title}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {statistics.stats.map((stat, index) => (
              <div key={index} className="text-center p-3 bg-gray-50 rounded-lg">
                <div className="text-2xl font-bold text-gray-900">{stat.value}</div>
                <div className="text-sm text-gray-600">{stat.label}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
